const express = require('express')
const fs = require('fs')
const path = require('path')
const cors = require('cors')
const csv = require('csv-parser')
const createCsvWriter = require('csv-writer').createObjectCsvWriter
const app = express()
const PORT = process.env.PORT || 3456

// 服务静态文件
app.use(express.static(path.join(__dirname, 'dist')))

// 确保CSV文件存在
const CSV_PATH = path.join(__dirname, 'src', 'assets', 'Info.csv')
if (!fs.existsSync(CSV_PATH)) {
  const defaultContent = `key,value
name,张三
title,前端开发工程师
description,热爱编程，专注于Vue.js和React开发，有5年工作经验。
email,zhangsan@example.com
phone,123-456-7890
avatar,https://via.placeholder.com/150
address,北京市朝阳区
website,https://example.com
github,https://github.com/zhangsan
linkedin,https://linkedin.com/in/zhangsan
twitter,https://twitter.com/zhangsan
facebook,https://facebook.com/zhangsan
instagram,https://instagram.com/zhangsan
wechat,zhangsan_wechat
birthday,1990-01-01
education,北京大学计算机科学与技术学士
skills,"JavaScript, Vue.js, React, Node.js, HTML, CSS"
languages,中文（母语），英语（流利）
interests,编程，阅读，旅行，摄影
projects,Vue电商平台，React社交媒体应用`
  fs.writeFileSync(CSV_PATH, defaultContent, 'utf-8')
}

// 启用CORS和JSON解析
app.use(cors({
  origin: 'http://localhost:5173', // 允许前端开发服务器
  credentials: true
}))
app.use(express.json())

// 添加一个测试路由
app.get('/api/test', (req, res) => {
  console.log('Received request to /api/test');
  res.json({ message: 'API is working' });
});

// 记录所有请求
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 获取个人信息
app.get('/api/info', (req, res) => {
  try {
    const results = {}
    fs.createReadStream(CSV_PATH)
      .pipe(csv())
      .on('data', (data) => {
        results[data.key] = data.value
      })
      .on('end', () => {
        res.json(results)
      })
      .on('error', (error) => {
        console.error('Error reading CSV file:', error)
        res.status(500).json({ error: 'Failed to read info file' })
      })
  } catch (error) {
    console.error('Unexpected error:', error)
    res.status(500).json({ error: 'Internal server error' })
  }
})

// 更新个人信息
app.post('/api/info', (req, res) => {
  try {
    const info = req.body
    const csvWriter = createCsvWriter({
      path: CSV_PATH,
      header: [
        {id: 'key', title: 'key'},
        {id: 'value', title: 'value'}
      ]
    })

    const data = Object.entries(info).map(([key, value]) => ({key, value}))

    csvWriter.writeRecords(data)
      .then(() => {
        res.json({ success: true })
      })
      .catch((error) => {
        console.error('Error writing CSV file:', error)
        res.status(500).json({ error: 'Failed to write info file' })
      })
  } catch (error) {
    console.error('Unexpected error:', error)
    res.status(500).json({ error: 'Internal server error' })
  }
})

// 处理所有其他路由
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

// 启动服务器
const server = app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server running at http://localhost:${PORT}`)
})

// 处理错误
server.on('error', (error) => {
  console.error('Server error:', error)
  if (error.code === 'EADDRINUSE') {
    console.log(`Port ${PORT} is already in use. Please use a different port.`)
    process.exit(1)
  }
})

// 优雅关闭
process.on('SIGINT', () => {
  console.log('Shutting down server...')
  server.close(() => {
    console.log('Server shut down')
    process.exit(0)
  })
})